package P8;

public class P8_myAtoi {

    public static void main(String[] args) throws Exception {

        System.out.println(new P8_myAtoi().myAtoi("+42"));
    }

    public int myAtoi(String s) {
        s = s.trim();

        if (s.length() == 0) {
            return 0;
        }

        boolean flag = true;
        if (s.charAt(0) == '-') {
            //负数
            flag = false;
            s = s.substring(1);
        } else if (s.charAt(0) == '+'){
            flag = true;
            s = s.substring(1);
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                sb.append(s.charAt(i));
            } else {
                break;
            }
        }

        if (sb.length() == 0) {
            return 0;
        }
        try {
            int result = Integer.valueOf(sb.toString());
            if (!flag) {
                result = -result;
            }
            return result;

        } catch (Exception e) {
            if (flag) {
                return Integer.MAX_VALUE;
            } else {
                return Integer.MIN_VALUE;
            }
        }
    }
}
